package com.skw.bio.oneToOne.message;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread{
    ServerSocket serverSocket = null;

    public Server(int port) {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server(6768);
        server.start();
    }

    @Override
    public void run() {
        super.run();
        try {
            System.out.println("服务器在启动中...等待用户的连接");
            while (true) {
                Socket socket = serverSocket.accept();
                OutputStream os = socket.getOutputStream();
                InputStream is = socket.getInputStream();

                os.write("服务器正向你发送消息".getBytes());
                System.out.println(socket.getInetAddress().getHostAddress() + " 连接上了！");
                //读取数据
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    //直接把获得的数据打印数来
                    System.out.println("服务器收到客户端的数据：" + new String(buf, 0, len));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
